package com.example.wyh.intelcheckbash.task;

import android.app.ActionBar;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.Image;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;

import com.example.wyh.intelcheckbash.MainActivity;
import com.example.wyh.intelcheckbash.R;
import com.example.wyh.intelcheckbash.SettingActivity;
import com.example.wyh.intelcheckbash.bug.BugRecordActivity;
import com.example.wyh.intelcheckbash.bug.CodeInfoActivity;
import com.example.wyh.intelcheckbash.common.SysExitUtil;

import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by chen on 17/10/31.
 */

public class CheckInfoActivity extends AppCompatActivity {
    JSONObject checkDetail;
    JSONObject xmInfo;
    String checkOrigin;
    String equipmentCode="";
    TextView check_info_standard;
    CheckBox check_info_pass_id;
    CheckBox check_info_dispass_id;
    TextView check_info_show_seismic_id;
    TextView check_info_show_cb_value;
    TextView cb_unit;
    CheckBox check_info_seismic_bug_check;
    TextView unit;
    Spinner linkMajorListSpinner;
    Spinner defectLevelSpinner;
    Spinner machineGroupSpinner;
    EditText link_name;
    EditText defect_description;
    TextView equipmentCodeText;
    TextView equipmentSystemText;
    TextView clear_equipment_code;

    LinearLayout CL;//测量
    LinearLayout GC;//观察
    LinearLayout CB;//抄表
    public  void  initActionBar(){
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("");
            actionBar.setDisplayShowHomeEnabled(false);
            actionBar.setDisplayShowCustomEnabled(true);
            LayoutInflater inflator = (LayoutInflater) this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = inflator.inflate(R.layout.actionbar_custom,new LinearLayout(CheckInfoActivity.this),false);
            android.support.v7.app.ActionBar.LayoutParams layout = new android.support.v7.app.ActionBar.LayoutParams(
                    android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT, android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT);
            actionBar.setCustomView(v, layout);
            Toolbar parent = (Toolbar) v.getParent();
            parent.setContentInsetsAbsolute(0, 0);
        }


        TextView actionBarTitle = (TextView) findViewById(R.id.action_bar_title);
        actionBarTitle.setText("巡检任务");
        ImageView title_logo = (ImageView)findViewById(R.id.title_logo_id);
        title_logo.setImageResource(R.drawable.check_task);

        RelativeLayout bar_back_btn =  (RelativeLayout) findViewById(R.id.bar_back_btn);
        bar_back_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CheckInfoActivity.this.finish();
            }
        });


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_info);
        SysExitUtil.activityList.add(CheckInfoActivity.this);
        checkDetail = getIntentDate("checkDetail");
        xmInfo = getIntentDate("xmInfo");
//        Log.e("xmInfo",xmInfo.toString());
//        Log.e("checkDetail",checkDetail.toString());
        checkOrigin = getIntent().getStringExtra("checkOrigin");
        try {
            equipmentCode = xmInfo.getString("equipment_code");
        }catch (JSONException e)
        {

        }

        initElement();
        initSpinner();
        initView();
        initActionBar();
        initAction();
    }

    public void initElement() {
        check_info_standard = (TextView) findViewById(R.id.check_info_standard);
        check_info_pass_id = (CheckBox) findViewById(R.id.check_info_pass_id);
        check_info_dispass_id = (CheckBox) findViewById(R.id.check_info_dispass_id);
        check_info_show_seismic_id = (TextView) findViewById(R.id.check_info_show_seismic_id);
        check_info_seismic_bug_check = (CheckBox) findViewById(R.id.check_info_seismic_bug_check);
        link_name = (EditText) findViewById(R.id.link_name);
        defect_description =  (EditText) findViewById(R.id.defect_description);
        equipmentCodeText = (TextView)findViewById(R.id.equipment_code);
        equipmentCodeText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivityForResult(new Intent(CheckInfoActivity.this,CodeInfoActivity.class),1000);
            }
        });
        equipmentSystemText = (TextView)findViewById(R.id.equipment_system);
        GC = (LinearLayout) findViewById(R.id.GC);
        CL = (LinearLayout) findViewById(R.id.CL);

        CB = (LinearLayout) findViewById(R.id.CB);
        check_info_show_cb_value = (TextView)findViewById(R.id.check_info_show_cb_value);
        cb_unit = (TextView)findViewById(R.id.cb_unit);

        unit = (TextView) findViewById(R.id.unit);
        clear_equipment_code = (TextView)findViewById(R.id.clear_equipment_code);
//        clear_equipment_code.setVisibility(View.INVISIBLE);
        clear_equipment_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                equipmentCodeText.setText("");
                clear_equipment_code.setVisibility(View.INVISIBLE);
            }
        });
    }

    public JSONObject getIntentDate(String key) {
        JSONObject data = new JSONObject();
        try {
            data = new JSONObject(getIntent().getStringExtra(key));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return data;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && resultCode == 1000) {
            try {
                JSONObject equipmentInfo = new JSONObject(data.getStringExtra("equipment_code"));
                equipmentCodeText.setText(equipmentInfo.getString("equipment_code"));
                if (equipmentCodeText.getText().length() > 0)
                {
                    clear_equipment_code.setVisibility(View.VISIBLE);
                }
                else
                {
                    clear_equipment_code.setVisibility(View.INVISIBLE);
                }
            } catch (JSONException e) {

            }

        }
    }

    public void initView() {
        equipmentCodeText.setText(equipmentCode);
        if (equipmentCodeText.getText().length() > 0)
        {
            clear_equipment_code.setVisibility(View.VISIBLE);
        }
        else
        {
            clear_equipment_code.setVisibility(View.INVISIBLE);
        }
        try {
            if (xmInfo.getString("sfycd").equals("1"))
            {
                defect_description.setText("异常");
            }
        }catch (JSONException e)
        {

        }

        equipmentSystemText.setText(checkOrigin);
        try {
            setTitle(checkDetail.getString("description"));
            check_info_standard.setText(checkDetail.getString("djbz"));
            check_info_seismic_bug_check.setChecked(xmInfo.getString("isqx").equals("1")? true: false);
            Log.e("checkDetail",checkDetail.toString());
            Log.e("checkOrigin",checkOrigin);
            Log.e("xmInfo",xmInfo.toString());

            if (checkDetail.getString("cdlx").equals("GC")) {
                JSONArray cdjgzlb = checkDetail.getJSONArray("cdjgzlb");
                check_info_pass_id.setText(cdjgzlb.getJSONObject(0).getString("z"));
                check_info_dispass_id.setText(cdjgzlb.getJSONObject(1).getString("z"));
                String correctValue = cdjgzlb.getJSONObject(0).getString("sfyc").equals("0")?cdjgzlb.getJSONObject(0).getString("z") : cdjgzlb.getJSONObject(1).getString("z");
                String errorValue = cdjgzlb.getJSONObject(0).getString("sfyc").equals("0")?cdjgzlb.getJSONObject(1).getString("z") : cdjgzlb.getJSONObject(0).getString("z");

                GC.setVisibility(View.VISIBLE);
                CL.setVisibility(View.GONE);
                CB.setVisibility(View.GONE);
                if(xmInfo.getString("cdjg").equals(correctValue)){
                    check_info_pass_id.setChecked(true);
                }
                if(xmInfo.getString("cdjg").equals(errorValue)){
                    check_info_dispass_id.setChecked(true);
                }

            }else if (checkDetail.getString("cdlx").equals("CB"))
            {
                CB.setVisibility(View.VISIBLE);
                CL.setVisibility(View.GONE);
                GC.setVisibility(View.GONE);
                check_info_show_cb_value.setText(xmInfo.getString("cdjg"));
                Log.e("cdlx","CB"+xmInfo.getString("cdjg"));
            }
            else {
                CB.setVisibility(View.GONE);
                CL.setVisibility(View.VISIBLE);
                GC.setVisibility(View.GONE);
                check_info_show_seismic_id.setText(xmInfo.getString("cdjg"));
            }

            String cddw = checkDetail.getString("cddw");
            if (cddw.equals("C")) {
                cddw = " ℃";
            }
            unit.setText(cddw);
            cb_unit.setText(cddw);

            try{
                link_name.setText(xmInfo.getString("lxr"));
            }catch (JSONException e){

            }
            try{
                linkMajorListSpinner.setSelection(getIndex(getLinkMajorList(), xmInfo.getString("lxzy")));
            }catch (JSONException e){

            }
            try{
                defectLevelSpinner.setSelection(getIndex(getDefectLevel(), xmInfo.getString("qxdj")));
            }catch (JSONException e){

            }
            try{
                defect_description.setText(xmInfo.getString("qxms"));
            }catch (JSONException e){

            }
            try {
                machineGroupSpinner.setSelection(getIndex(getMachineGroupList(),xmInfo.getString("jz")));
            }catch (Exception e)
            {

            }

        } catch (JSONException e) {
            Log.e("JSONException",e.toString());
        }
    }

    private ArrayList getDefectLevel() {
        ArrayList list = new ArrayList<String>();
        list.add("一类缺陷");
        list.add("二类缺陷");
        list.add("三类缺陷");
        return list;
    }
    private  ArrayList getMachineGroupList(){
        ArrayList list = new ArrayList<String>();
        list.add("脱硫");
        list.add("网控");
        list.add("燃料");
        list.add("#1机组");
        list.add("厂外");
        list.add("#2机组");
        list.add("公用系统");
        return list;
    }

    private ArrayList getLinkMajorList() {
        ArrayList list = new ArrayList<String>();
        list.add("汽机");
        list.add("电气一次");
        list.add("电气二次");
        list.add("锅炉");
        list.add("热控");
        list.add("燃料");
        list.add("化学");
        list.add("脱硫");
        list.add("脱硝");
        list.add("除灰");
        list.add("信息");

        return list;
    }
    public  int getIndex(ArrayList list, String str){
        Integer index = 0;
        for(int i =0; i < list.size();i++){
            if(list.get(i).equals(str)){
                index = i;
                break;
            }
        }
        return  index;
    }
    public void initSpinner() {
        ArrayList linkMajorList = getLinkMajorList();
         linkMajorListSpinner = initSpinner("联系专业", R.id.link_major, linkMajorList);
        ArrayList defectLevel = getDefectLevel();
        defectLevelSpinner = initSpinner("缺陷等级", R.id.defect_level, defectLevel);
        defectLevelSpinner.setSelection(2);
        ArrayList machineGroupList = getMachineGroupList();
        machineGroupSpinner = initSpinner("机组",R.id.machine_group,machineGroupList);
    }

    public Spinner initSpinner(String title, Integer id, ArrayList data) {
        final Spinner spinner = (Spinner) findViewById(id);
        spinner.setPrompt(title);
        spinner.setSelection(0);
        ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                spinner.setSelection(position);
                //todo
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        return spinner;
    }
    public  void  initAction(){
        Button save_btn = (Button) findViewById(R.id.save_btn);
        save_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JSONObject defectInfo = new JSONObject();
                EditText link_name =  (EditText) findViewById(R.id.link_name);
                Spinner defect_level=(Spinner) findViewById(R.id.defect_level);
                Spinner link_major=(Spinner) findViewById(R.id.link_major);
                try {
                    defectInfo.put("lxr", link_name.getText().toString());
                    defectInfo.put("qxms", defect_description.getText().toString());
                    defectInfo.put("qxdj", defect_level.getSelectedItem().toString());
                    defectInfo.put("lxzy", link_major.getSelectedItem().toString());
                    String isqx = check_info_seismic_bug_check.isChecked() ? "1":"0";
                    defectInfo.put("isqx",isqx);
                    defectInfo.put("jz",machineGroupSpinner.getSelectedItem().toString());
                    defectInfo.put("equipment_code",equipmentCodeText.getText().toString());
                    defectInfo.put("sbxt",checkOrigin);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Intent data = new Intent(CheckInfoActivity.this, TaskCheckActivity.class);
                data.putExtra("defectInfo", defectInfo.toString());
                Log.e("defectInfo=======",defectInfo.toString());
                Log.e("xminfo========",xmInfo.toString());
                // TODO: 17/12/29 添加缺陷或者异常限制
                try {
                    if (defectInfo.getString("isqx").equals("0") && xmInfo.getString("sfycd").equals("0"))
                    {
                        setResult(1001,data);
                        CheckInfoActivity.this.finish();
                    }
                    else
                    {
                        try {
                            if (defectInfo.getString("isqx").equals("1") &&
                                    (defectInfo.getString("qxms").length() == 0
                                            ||defectInfo.getString("qxdj").length() == 0
                                            || defectInfo.getString("lxzy").length() == 0
                                            || defectInfo.getString("lxr").length() == 0))
                            {
                                // TODO: 17/12/29 缺陷详情没有填写完整弹框
                                showUnCompleteQXYCAlert("此项目为缺陷项，请核实缺陷描述,缺陷等级,联系专业,联系人是否都填写完整？");
                                return;
                            }
                        }catch (JSONException e)
                        {

                        }
                        try {
                            if (xmInfo.getString("sfycd").equals("1") && defectInfo.getString("qxms").length() == 0)
                            {
                                // TODO: 17/12/29 异常详情没有填写完整
                                showUnCompleteQXYCAlert("此项目为异常项，请核实异常描述是否填写完整？");
                                return;
                            }
                        }catch (JSONException e)
                        {

                        }
                        setResult(1001,data);
                        CheckInfoActivity.this.finish();
                    }
                }catch (JSONException e)
                {

                }


            }
        });

    }

    public void showUnCompleteQXYCAlert(String msg)
    {
        LayoutInflater layoutInflater = LayoutInflater.from(CheckInfoActivity.this);
        final View layout = layoutInflater.inflate(R.layout.alert_dialog,
                null);
        final AlertDialog alertDialog = new AlertDialog.Builder(CheckInfoActivity.this).setTitle("").setView(layout)
                .setPositiveButton("", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .setNegativeButton("", null).show();

        TextView alert_title = (TextView) layout.findViewById(R.id.alert_title);
        alert_title.setText(msg);
        Button confirm = (Button) layout.findViewById(R.id.alert_confirm);
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
        Button cancle = (Button) layout.findViewById(R.id.alert_cancle);
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event)
//    {
//        if(keyCode == KeyEvent.KEYCODE_BACK){
//            Intent data = new Intent();
//            data.putExtra("testValue", "44");
//            this.setResult(0, data);
//            this.finish();
//        }
//
//        return super.onKeyDown(keyCode, event);
//    }
//

}
